<template>
    <div class="app-container">
        <!-- 下拉选择学期 -->
        <div style="display: flex;">
            <el-select
                class="semester-select"
                @change="handleSelectChange"
                v-model="selectedSemesterId"
                placeholder="请选择学期"
                clearable
                style="width: 200px;"
            >
                <el-option
                    v-for="item in semesterData"
                    :key="item.id"
                    :value="item.id"
                    :label="item.semesterName"
                ></el-option>
            </el-select>
            <!-- 执行排课 -->
            <el-button
                style="margin-left: 10px"
                type="primary"
                :disabled="!selectedSemesterId"
                :loading="loading"
                @click="confirmArrangeCourse"
            >
                执行排课算法
                <el-icon class="el-icon--right"><Tools /></el-icon>
            </el-button>
        </div>
        <br />

        <!-- 展示上传后的结果 -->
        <el-table
            v-loading="listLoading"
            :data="paginatedList"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
        >
            <el-table-column align="center" label="ID" width="60px">
                <template #default="scope">
                    {{ scope.$index + 1 + (currentPage - 1) * pageSize }}
                </template>
            </el-table-column>
            <el-table-column label="班级编号" prop="classNo" align="center">
                <template #default="scope">
                    {{ scope.row.classNo }}
                </template>
            </el-table-column>
            <el-table-column label="班级名" prop="className" align="center">
                <template #default="scope">
                    <span>{{ scope.row.className }}</span>
                </template>
            </el-table-column>
            <el-table-column label="教师编号" prop="teacherNo" align="center">
                <template #default="scope">
                    {{ scope.row.teacherNo }}
                </template>
            </el-table-column>
            <el-table-column label="教师姓名" prop="teacherName" align="center">
                <template #default="scope">
                    <span>{{ scope.row.teacherName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="课程编号" prop="courseNo" align="center">
                <template #default="scope">
                    {{ scope.row.courseNo }}
                </template>
            </el-table-column>
            <el-table-column label="课程名" prop="courseName" align="center">
                <template #default="scope">
                    <span>{{ scope.row.courseName }}</span>
                </template>
            </el-table-column>

            <!-- 其他字段 -->
            <el-table-column label="课程属性" prop="courseAttr" align="center">
                <template #default="scope">
                    {{ scope.row.courseAttr }}
                </template>
            </el-table-column>

            <el-table-column label="总周数" prop="weeksSum" align="center">
                <template #default="scope">
                    {{ scope.row.weeksSum }}
                </template>
            </el-table-column>
            <el-table-column label="周学时" prop="weeksNumber" align="center">
                <template #default="scope">
                    {{ scope.row.weeksNumber }}
                </template>
            </el-table-column>

            <el-table-column label="开始周" prop="startWeek" align="center">
                <template #default="scope">
                    {{ scope.row.startWeek }}
                </template>
            </el-table-column>
            <el-table-column label="结束周" prop="endWeek" align="center">
                <template #default="scope">
                    {{ scope.row.endWeek }}
                </template>
            </el-table-column>
            <el-table-column label="单双周" prop="biweekly" align="center">
                <template #default="scope">
                    {{ scope.row.biweekly }}
                </template>
            </el-table-column>
            <el-table-column label="教学区域编号" prop="areaNo" align="center">
                <template #default="scope">
                    {{ scope.row.areaNo }}
                </template>
            </el-table-column>
            <el-table-column label="同时上课班数" prop="classCount" align="center">
                <template #default="scope">
                    {{ scope.row.classCount }}
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            style="margin-top: 1rem; margin-left: 0.4rem"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="list.length" 
        >
        </el-pagination>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Tools } from '@element-plus/icons-vue'; 
import axios from 'axios'; // 或者您的axios实例路径


const router = useRouter();
// const semesterStore = useSemesterStore(); // 如果使用Pinia

const semesterData = ref([]);
const list = ref([]);
const listLoading = ref(true);
const selectedSemesterId = ref(null); // 替换了之前的 value 和 id
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);

// 计算属性用于分页
const paginatedList = computed(() => {
    if (!list.value) return [];
    return list.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value);
});

const getSemester = async () => {
    listLoading.value = true;
    try {
        const res = await axios.get("/api/semester/getList",{
          headers: {
            "token": localStorage.getItem("token"),
          },
        });
        // const res = await proxy.$axios.get("/semester/getList"); // 使用 proxy.$axios
        semesterData.value = res.data.data || [];
    } catch (error) {
        console.error("查询学期失败", error);
        ElMessage.error("查询学期列表失败");
    } finally {
        // listLoading.value = false; // 通常在获取主列表数据后关闭loading
    }
};

const fetchAllClassTask = async () => {
    listLoading.value = true;
    try {
        const res = await axios.get("/api/task/getList", {
            headers: {
                token: localStorage.getItem("token"),
            },
        });
        // const res = await proxy.$axios.get("/task/getList", { // 使用 proxy.$axios
        //     headers: {
        //         Authorization: localStorage.getItem("token"),
        //     },
        // });
        list.value = res.data.data || [];
        if (list.value.length === 0) {
            ElMessage.info("查询不到开课任务"); // Element Plus 推荐用 info
        }
    } catch (error) {
        console.error("查询开课任务失败", error);
        ElMessage.error("查询开课任务失败");
    } finally {
        listLoading.value = false;
    }
};

onMounted(() => {
    fetchAllClassTask();
    getSemester();
});

const handleSelectChange = (val) => {
    selectedSemesterId.value = val;
    // 如果选择学期后需要重新加载任务列表，可以在这里调用 fetchAllClassTask
    // 不过当前逻辑似乎是独立的，排课按钮的disabled状态依赖于selectedSemesterId
};

const confirmArrangeCourse = () => {
    const selectedSemester = semesterData.value.find(item => item.id === selectedSemesterId.value);
    if (!selectedSemester) {
        ElMessage.warning('未找到选中的学期信息');
        return;
    }

    if (selectedSemester.semesterStatus == 1) {
        ElMessageBox.confirm('该学期已排课，坚持排课将覆盖之前排课内容, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            arrangeCourse();
        }).catch(() => {
            ElMessage.info('已取消排课');
        });
    } else {
        arrangeCourse();
    }
};

const arrangeCourse = async () => {
    if (!selectedSemesterId.value) {
        ElMessage.warning('请先选择一个学期');
        return;
    }
    loading.value = true;
    ElMessage.info("开始排课");
    try {
        await axios.post(`/api/task/autoSchedule/${selectedSemesterId.value}`, {}, { // POST请求通常第二个参数是body
            headers: {
                token: localStorage.getItem("token"),
            },
        });
        // await proxy.$axios.post(`/task/autoSchedule/${selectedSemesterId.value}`, {}, { // 使用 proxy.$axios
        //      headers: {
        //          Authorization: localStorage.getItem("token"),
        //      },
        //  });
        await fetchAllClassTask(); // 重新获取任务列表，可能排课后有更新
        ElMessage.success("排课成功");
        // proxy.$store.commit('SET_SEMESTERID', selectedSemesterId.value); // 使用Pinia或其他方式替代
        // semesterStore.setSemesterId(selectedSemesterId.value); // Pinia 示例
        router.push("/scheduling/handle");
    } catch (error) {
        console.error("排课失败", error);
        ElMessage.error("排课失败，请查看控制台获取更多信息。");
    } finally {
        loading.value = false;
    }
};

const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1; // 通常改变每页数量时回到第一页
    // fetchAllClassTask(); // 如果分页是后端分页，则需要重新获取数据
};

const handleCurrentChange = (val) => {
    currentPage.value = val;
    // fetchAllClassTask(); // 如果分页是后端分页，则需要重新获取数据
};

// Vue 3 不再有 filters，如果需要类似功能，可以直接在模板中使用方法或计算属性
// 例如，如果之前有 statusFilter，可以这样：
// const getStatusText = (status) => { /* ... */ };
// 然后在模板中： {{ getStatusText(scope.row.status) }}

</script>

<style scoped>
.app-container {
    padding: 20px;
}
.semester-select {
    margin-bottom: 20px;
}
/* 您可以根据需要添加或调整样式 */
</style>
  